#include "cameraserverthread.h"
#include "NetworkCommonFunction.h"
#include "pendingcameraconnection.h"

#include <QDebug>
extern "C"
{
#include <winsock2.h>
}

CameraServerThread* CameraServerThread::createCameraServerThread()
{
	static CameraServerThread* thread = new CameraServerThread;
	thread->start();
	return thread;
}

CameraServerThread::CameraServerThread()
{
}

void CameraServerThread::run()
{
	SOCKET sockFd = socket(AF_INET, SOCK_STREAM, 0);
	if(sockFd == INVALID_SOCKET)
	{
		emit errorHappened(CreateSocketError);
		return;
	}

	int option = 1;
	int ret = setsockopt(sockFd, SOL_SOCKET, SO_REUSEADDR, (char*)&option, sizeof(option));
	if(ret == SOCKET_ERROR)
	{
		qDebug()<<"Set socket reuse address error";
	}

	SOCKADDR_IN dataServerAddress;
	dataServerAddress.sin_family = AF_INET;
	dataServerAddress.sin_addr.s_addr = htonl(INADDR_ANY);
	dataServerAddress.sin_port = htons(1115);

	if(bind(sockFd, (SA*)&dataServerAddress, sizeof(dataServerAddress)) == SOCKET_ERROR)
	{
		emit errorHappened(BindError);
		qDebug()<<"Bind camera client error";
		return;
	}

	if(listen(sockFd, SOMAXCONN) == SOCKET_ERROR)
	{
		emit errorHappened(ListenError);
		qDebug()<<"Listen camera client error";
		return;
	}

	while(true)
	{
		SOCKET clientSocket;
		SOCKADDR_IN clientAddress;
		int clientAddressSize = sizeof(clientAddress);
		clientSocket = accept(sockFd, (SA*)&clientAddress, &clientAddressSize);
		if(clientSocket == INVALID_SOCKET)
		{
			emit errorHappened(AcceptError);
			qDebug()<<"Accept camera client error";
			continue;
		}
		PendingCameraConnection* pendingCameraConnection = new PendingCameraConnection(clientSocket);
		pendingCameraConnection->start();
	}
}
